import React, { useState, useEffect, useContext } from 'react';
import { Student } from '../../../shared/models';
import { DataContext } from '../../../shared/DataContext';
import './AddEditStudentModal.css';

interface AddEditStudentModalProps {
  isOpen: boolean;
  isEditing: boolean;
  student: Student | null;
  onClose: () => void;
  onSave: (student: Omit<Student, 'id'>) => void;
}

const AddEditStudentModal: React.FC<AddEditStudentModalProps> = ({
  isOpen,
  isEditing,
  student,
  onClose,
  onSave,
}) => {
  // 从数据上下文获取数据，包括classes
  const { dormitories, classes, statusOptions, stageOptions, academyOptions } = useContext(DataContext);
  
  // 根据班级名称获取阶层和阶段信息
  const getClassInfo = (className: string) => {
    const classInfoMap: { [key: string]: { tier: string, stage: string } } = {
      // 专业阶段班级
      '2509A': { tier: '专业', stage: '专业阶段' },
      '2508A': { tier: '专业', stage: '专业阶段' },
      '2508B': { tier: '专业', stage: '专业阶段' },
      '2507A': { tier: '专业', stage: '专业阶段' },
      '2507B': { tier: '专业', stage: '专业阶段' },
      '2506A': { tier: '专业', stage: '专业阶段' },
      '2505A': { tier: '专业', stage: '专业阶段' },
      // 专高阶段班级
      '2504A': { tier: '专高', stage: '专高阶段' },
      '2503A': { tier: '专高', stage: '专高阶段' },
      '2502A': { tier: '专高', stage: '专高阶段' },
      '2502C': { tier: '专高', stage: '专高阶段' },
      '2501A': { tier: '专高', stage: '专高阶段' },
      '2412A': { tier: '专高', stage: '专高阶段' },
      '2412C': { tier: '专高', stage: '专高阶段' },
      '2411A': { tier: '专高', stage: '专高阶段' },
      '2411B': { tier: '专高', stage: '专高阶段' },
      '2411C': { tier: '专高', stage: '专高阶段' },
      // 实训阶段班级
      '2410A': { tier: '实训', stage: '实训阶段' },
      '2410B': { tier: '实训', stage: '实训阶段' },
      '2410C': { tier: '实训', stage: '实训阶段' },
      '2410D': { tier: '实训', stage: '实训阶段' },
      '2409A': { tier: '实训', stage: '实训阶段' },
      '2409B': { tier: '实训', stage: '实训阶段' },
      '2409C': { tier: '实训', stage: '实训阶段' },
      '2408A': { tier: '实训', stage: '实训阶段' },
      '2408B': { tier: '实训', stage: '实训阶段' }
    };
    return classInfoMap[className] || { tier: '未知', stage: '未知' };
  };

  // 阶层选项
  const tierOptions = [
    { value: '专业', label: '专业' },
    { value: '专高', label: '专高' },
    { value: '实训', label: '实训' }
  ];

  // 表单状态 - 统一使用正确的字段名
  const [formData, setFormData] = useState<Partial<Student & { tier: string }>>({
    studentId: '',
    name: '',
    gender: 'male',
    tier: '',
    stage: '',
    academy: '',
    classId: '',
    dateOfBirth: new Date().toISOString().split('T')[0],
    phoneNumber: '',
    email: '',
    address: '',
    dormitoryId: '',
    status: 'active',
    admissionDate: new Date().toISOString().split('T')[0],
    emergencyContact: {
      name: '',
      relationship: '',
      phone: ''
    }
  });

  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isSubmitting, setIsSubmitting] = useState(false); // 添加提交状态

  // 当学生性别改变时，重置宿舍选择
  useEffect(() => {
    if (formData.gender && formData.dormitoryId) {
      const selectedDorm = dormitories.find(d => d.id === formData.dormitoryId);
      if (selectedDorm && selectedDorm.type !== formData.gender) {
        setFormData(prev => ({ ...prev, dormitoryId: '' }));
        setErrors(prev => ({ ...prev, dormitoryId: '宿舍类型与学生性别不匹配' }));
      } else {
        // 清除错误
        setErrors(prev => { 
          const newErrors = { ...prev };
          delete newErrors.dormitoryId;
          return newErrors;
        });
      }
    }
  }, [formData.gender, formData.dormitoryId, dormitories]);
  
  // 当编辑的学生变化时，更新表单数据
  useEffect(() => {
    if (isEditing && student) {
      // 统一使用dateOfBirth和admissionDate字段名，确保字段一致性
      const safeDateOfBirth = student.dateOfBirth && !isNaN(new Date(student.dateOfBirth).getTime()) 
        ? new Date(student.dateOfBirth).toISOString().split('T')[0]
        : (student.birthdate && !isNaN(new Date(student.birthdate).getTime())
          ? new Date(student.birthdate).toISOString().split('T')[0]
          : new Date().toISOString().split('T')[0]);
      
      const safeAdmissionDate = student.admissionDate && !isNaN(new Date(student.admissionDate).getTime())
        ? new Date(student.admissionDate).toISOString().split('T')[0]
        : (student.enrollmentDate && !isNaN(new Date(student.enrollmentDate).getTime())
          ? new Date(student.enrollmentDate).toISOString().split('T')[0]
          : new Date().toISOString().split('T')[0]);
      
      // 获取学生班级的阶层信息
      let tier = '';
      if (student.classId) {
        const studentClass = classes.find(c => c.id === student.classId);
        if (studentClass) {
          const classInfo = getClassInfo(studentClass.name);
          tier = classInfo.tier;
        }
      }
      
      setFormData({
        ...student,
        tier,
        dateOfBirth: safeDateOfBirth,
        admissionDate: safeAdmissionDate,
        dormitoryId: student.dormitoryId || '',
        emergencyContact: student.emergencyContact || { name: '', relationship: '', phone: '' }
      });
    } else if (!isEditing && isOpen) {
      // 重置为默认值
      const today = new Date().toISOString().split('T')[0];
      setFormData({
        studentId: '',
        name: '',
        gender: 'male',
        tier: '',
        stage: '',
        academy: '',
        classId: '',
        dateOfBirth: today,
        phoneNumber: '',
        email: '',
        address: '',
        dormitoryId: '',
        status: 'active',
        admissionDate: today,
        emergencyContact: {
          name: '',
          relationship: '',
          phone: ''
        }
      });
    }
    setErrors({});
    setIsSubmitting(false);
  }, [isEditing, student, isOpen]);

  // 表单输入处理
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    
    // 如果是嵌套对象的字段
    if (name.includes('.')) {
      const [parent, child] = name.split('.');
      setFormData(prev => ({
        ...prev,
        [parent]: {
          ...prev[parent] as object,
          [child]: value
        }
      }));
    } else {
      // 特殊处理数字字段
      if (name === 'classId') {
        const classId = value;
        const selectedClass = classes?.find(c => c.id === classId);
        
        let updates: Partial<Student & { tier: string }> = {
          classId,
          // 自动填充学院
          ...(selectedClass && {
            academy: selectedClass.academy
          })
        };
        
        // 如果选择了班级，根据班级信息设置阶段和阶层
        if (selectedClass) {
          const classInfo = getClassInfo(selectedClass.name);
          // 找到对应的stage value
          const stageOption = stageOptions.find(option => option.label === classInfo.stage);
          updates = {
            ...updates,
            stage: stageOption?.value || selectedClass.stage,
            tier: classInfo.tier
          };
        }
        
        setFormData(prev => ({ ...prev, ...updates }));
      } else if (name === 'stage' || name === 'academy' || name === 'tier') {
        // 当阶段、学院或阶层变更时，重置班级选择
        setFormData(prev => ({ 
          ...prev, 
          [name]: value,
          classId: ''
        }));
      } else {
        setFormData(prev => ({ ...prev, [name]: value }));
      }
    }
    
    // 清除对应字段的错误
    if (errors[name]) {
      setErrors((prev) => { const newErrors = { ...prev }; delete newErrors[name]; return newErrors; });
    }
    
    // 当阶段、学院或阶层变更时，也清除班级的错误
    if ((name === 'stage' || name === 'academy' || name === 'tier') && errors.classId) {
      setErrors((prev) => { const newErrors = { ...prev }; delete newErrors.classId; return newErrors; });
    }
  };

  // 处理班级选择变化 - 现在已集成到handleInputChange中

  // 表单验证
  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    // 必填字段验证
    if (!formData.studentId?.trim()) {
      newErrors.studentId = '学号不能为空';
    }

    if (!formData.name?.trim()) {
      newErrors.name = '姓名不能为空';
    }

    if (!formData.tier) {
      newErrors.tier = '请选择阶层';
    }

    if (!formData.stage) {
      newErrors.stage = '请选择阶段';
    }

    if (!formData.academy) {
      newErrors.academy = '请选择学院';
    }

    if (!formData.classId) {
      newErrors.classId = '请选择班级';
    }

    if (!formData.dateOfBirth) {
      newErrors.dateOfBirth = '出生日期不能为空';
    } else {
      // 验证出生日期的合理性
      const birthDate = new Date(formData.dateOfBirth);
      const today = new Date();
      const minAge = 12; // 最小12岁
      const maxAge = 25; // 最大25岁
      const age = today.getFullYear() - birthDate.getFullYear();
      
      if (age < minAge || age > maxAge) {
        newErrors.dateOfBirth = `学生年龄应在${minAge}-${maxAge}岁之间`;
      }
    }

    if (!formData.phoneNumber?.trim()) {
      newErrors.phoneNumber = '联系电话不能为空';
    } else if (!/^1[3-9]\d{9}$/.test(formData.phoneNumber)) {
      newErrors.phoneNumber = '请输入有效的手机号码';
    }

    if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = '请输入有效的邮箱地址';
    }

    if (!formData.admissionDate) {
      newErrors.admissionDate = '入学日期不能为空';
    } else {
      // 验证入学日期不能早于出生日期过多
      const birthDate = new Date(formData.dateOfBirth || 0);
      const admissionDate = new Date(formData.admissionDate);
      const minYearsBetween = 15; // 最小15年差距
      const yearsBetween = admissionDate.getFullYear() - birthDate.getFullYear();
      
      if (yearsBetween < minYearsBetween) {
        newErrors.admissionDate = '入学日期与出生日期不匹配';
      }
    }

    // 验证紧急联系人信息（如果填写了任一字段）
    if (formData.emergencyContact) {
      const { name, phone } = formData.emergencyContact;
      if (name || phone) {
        if (!name?.trim()) {
          newErrors['emergencyContact.name'] = '联系人姓名不能为空';
        }
        if (!phone?.trim()) {
          newErrors['emergencyContact.phone'] = '联系人电话不能为空';
        } else if (!/^1[3-9]\d{9}$/.test(phone)) {
          newErrors['emergencyContact.phone'] = '请输入有效的联系人手机号码';
        }
      }
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 设置提交状态，防止重复提交
    setIsSubmitting(true);
    
    try {
      // 额外验证宿舍选择
      const dormErrors: Record<string, string> = {};
      if (formData.dormitoryId) {
        const selectedDorm = dormitories.find(d => d.id === formData.dormitoryId);
        if (!selectedDorm) {
          dormErrors.dormitoryId = '选择的宿舍不存在';
        } else if (selectedDorm.type !== 'mixed' && selectedDorm.type !== formData.gender) {
          dormErrors.dormitoryId = '宿舍类型与学生性别不匹配';
        }
      }
      
      setErrors(prev => ({ ...prev, ...dormErrors }));
      
      if (Object.keys(dormErrors).length > 0) {
        return;
      }
      
      if (validateForm()) {
        // 创建新的学生数据，转换日期格式
        const newStudent = {
          ...formData,
          dateOfBirth: formData.dateOfBirth ? new Date(formData.dateOfBirth).toISOString() : new Date().toISOString(),
          admissionDate: formData.admissionDate ? new Date(formData.admissionDate).toISOString() : new Date().toISOString(),
          dormitoryId: formData.dormitoryId || undefined,
          // 移除可能存在的旧字段名
          birthdate: undefined,
          enrollmentDate: undefined
        } as Omit<Student, 'id'>;
        
        onSave(newStudent);
      }
    } catch (error) {
      console.error('提交表单时出错:', error);
      alert('提交失败，请稍后重试');
    } finally {
      setIsSubmitting(false);
    }
  };

  // 处理模态框关闭
  const handleClose = () => {
    // 重置表单状态
    setFormData({
      id: '',
      studentId: '',
      name: '',
      gender: 'male',
      tier: '',
      stage: '',
      academy: '',
      classId: '',
      className: '',
      dateOfBirth: new Date().toISOString().split('T')[0],
      phoneNumber: '',
      email: '',
      address: '',
      dormitoryId: '',
      status: 'active',
      admissionDate: new Date().toISOString().split('T')[0],
      emergencyContact: {
        name: '',
        relationship: '',
        phone: ''
      }
    });
    setErrors({});
    setIsSubmitting(false);
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="modal-overlay" onClick={handleClose}>
      <div className="modal-content" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <h2>{isEditing ? '编辑学生' : '添加学生'}</h2>
          <button className="modal-close" onClick={handleClose}>
            &times;
          </button>
        </div>

        <form onSubmit={handleSubmit} className="student-form">
          <div className="form-row">
            <div className="form-group">
              <label htmlFor="studentId">学号 <span className="required">*</span></label>
              <input
                type="text"
                id="studentId"
                name="studentId"
                value={formData.studentId}
                onChange={handleInputChange}
                placeholder="请输入学号"
                className={errors.studentId ? 'error' : ''}
                disabled={isEditing} // 编辑时学号不可修改
              />
              {errors.studentId && <span className="error-message">{errors.studentId}</span>}
            </div>

            <div className="form-group">
              <label htmlFor="name">姓名 <span className="required">*</span></label>
              <input
                type="text"
                id="name"
                name="name"
                value={formData.name}
                onChange={handleInputChange}
                placeholder="请输入姓名"
                className={errors.name ? 'error' : ''}
              />
              {errors.name && <span className="error-message">{errors.name}</span>}
            </div>
          </div>

          <div className="form-row">
            <div className="form-group">
              <label htmlFor="gender">性别</label>
              <select
                id="gender"
                name="gender"
                value={formData.gender}
                onChange={handleInputChange}
              >
                <option value="male">男</option>
                <option value="female">女</option>
              </select>
            </div>

            <div className="form-group">
              <label htmlFor="stage">阶段 <span className="required">*</span></label>
              <select
                id="stage"
                name="stage"
                value={formData.stage}
                onChange={handleInputChange}
                className={errors.stage ? 'error' : ''}
              >
                <option value="">请选择阶段</option>
                {/* 直接定义并显示三个主阶段选项 */}
                {[
                  { value: '专业阶段', label: '专业阶段' },
                  { value: '专高阶段', label: '专高阶段' },
                  { value: '实训阶段', label: '实训阶段' }
                ].map(option => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
              {errors.stage && <span className="error-message">{errors.stage}</span>}
            </div>

            <div className="form-group">
              <label htmlFor="tier">阶层 <span className="required">*</span></label>
              <select
                id="tier"
                name="tier"
                value={formData.tier}
                onChange={handleInputChange}
                className={errors.tier ? 'error' : ''}
              >
                <option value="">请选择阶层</option>
                {/* 直接定义并显示三个阶层选项 */}
                {[
                  { value: '专业', label: '专业' },
                  { value: '专高', label: '专高' },
                  { value: '实训', label: '实训' }
                ].map(option => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
              {errors.tier && <span className="error-message">{errors.tier}</span>}
            </div>
          </div>

          <div className="form-row">
            <div className="form-group">
              <label htmlFor="academy">学院 <span className="required">*</span></label>
              <select
                id="academy"
                name="academy"
                value={formData.academy}
                onChange={handleInputChange}
                className={errors.academy ? 'error' : ''}
              >
                <option value="">请选择学院</option>
                {academyOptions.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
              {errors.academy && <span className="error-message">{errors.academy}</span>}
            </div>
          </div>

          <div className="form-row">
            <div className="form-group">
              <label htmlFor="classId">班级 <span className="required">*</span></label>
              <select
                id="classId"
                name="classId"
                value={formData.classId || ''}
                onChange={handleInputChange}
                className={errors.classId ? 'error' : ''}
              >
                <option value="">请选择班级</option>
                {classes && classes.length > 0 ? (
                  classes
                    .filter(cls => {
                      // 首先检查是否有阶段筛选
                      let stageMatch = true;
                      if (formData.stage) {
                        // 获取阶段值对应的阶段名称
                        const selectedStage = stageOptions.find(option => option.value === formData.stage);
                        if (selectedStage) {
                          // 根据阶段名称从getClassInfo中筛选班级
                          const classesForStage = Object.keys(getClassInfo)
                            .filter(className => {
                              const info = getClassInfo(className);
                              return info.stage === selectedStage.label;
                            });
                          // 检查当前班级名称是否在对应阶段的班级列表中
                          stageMatch = classesForStage.includes(cls.name);
                        } else {
                          // 如果找不到对应的阶段选项，使用原始的阶段比较
                          stageMatch = cls.stage === formData.stage;
                        }
                      }
                      // 学院筛选 - 确保市场部选项能正常工作
                      const academyMatch = !formData.academy || cls.academy === formData.academy;
                      return stageMatch && academyMatch;
                    })
                    .map(cls => (
                      <option key={cls.id} value={cls.id}>
                        {cls.name}
                      </option>
                    ))
                ) : (
                  <option value="" disabled>暂无班级数据</option>
                )}
              </select>
              {errors.classId && <span className="error-message">{errors.classId}</span>}
            </div>

            <div className="form-group">
              <label htmlFor="dateOfBirth">出生日期 <span className="required">*</span></label>
              <input
                type="date"
                id="dateOfBirth"
                name="dateOfBirth"
                value={formData.dateOfBirth}
                onChange={handleInputChange}
                className={errors.dateOfBirth ? 'error' : ''}
                max={new Date().toISOString().split('T')[0]}
              />
              {errors.dateOfBirth && <span className="error-message">{errors.dateOfBirth}</span>}
            </div>
          </div>

          <div className="form-row">
            <div className="form-group">
              <label htmlFor="phoneNumber">联系电话 <span className="required">*</span></label>
              <input
                type="tel"
                id="phoneNumber"
                name="phoneNumber"
                value={formData.phoneNumber}
                onChange={handleInputChange}
                className={errors.phoneNumber ? 'error' : ''}
                placeholder="请输入手机号码"
              />
              {errors.phoneNumber && <span className="error-message">{errors.phoneNumber}</span>}
            </div>

            <div className="form-group">
              <label htmlFor="email">邮箱</label>
              <input
                type="email"
                id="email"
                name="email"
                value={formData.email}
                onChange={handleInputChange}
                placeholder="请输入邮箱地址"
                className={errors.email ? 'error' : ''}
              />
              {errors.email && <span className="error-message">{errors.email}</span>}
            </div>
          </div>

          <div className="form-row">
            <div className="form-group">
              <label htmlFor="status">状态</label>
              <select
                id="status"
                name="status"
                value={formData.status}
                onChange={handleInputChange}
              >
                {statusOptions.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            </div>

            <div className="form-group">
              <label htmlFor="admissionDate">入学日期 <span className="required">*</span></label>
              <input
                type="date"
                id="admissionDate"
                name="admissionDate"
                value={formData.admissionDate}
                onChange={handleInputChange}
                className={errors.admissionDate ? 'error' : ''}
                max={new Date().toISOString().split('T')[0]}
              />
              {errors.admissionDate && <span className="error-message">{errors.admissionDate}</span>}
            </div>
          </div>

          <div className="form-group full-width">
            <label htmlFor="address">家庭地址</label>
            <textarea
              id="address"
              name="address"
              value={formData.address || ''}
              onChange={handleInputChange}
              placeholder="请输入家庭地址"
              rows={3}
            ></textarea>
          </div>
          
          <div className="form-group">
            <label htmlFor="dormitoryId">宿舍</label>
            <select
              id="dormitoryId"
              name="dormitoryId"
              value={formData.dormitoryId || ''}
              onChange={handleInputChange}
              className={errors.dormitoryId ? 'error' : ''}
            >
              <option value="">请选择宿舍</option>
              {dormitories?.length > 0 ? (
                dormitories
                  .filter(dorm => {
                    // 根据学生性别筛选宿舍
                    return dorm.type === formData.gender;
                  })
                  .map(dorm => {
                    let displayText = `${dorm.building}-${dorm.roomNumber}`;
                    let optionClass = '';
                    
                    // 根据宿舍状态添加样式和提示
                    if (dorm.status === 'maintenance') {
                      displayText += '（维修中）';
                      optionClass = 'dorm-status-maintenance';
                    } else if (dorm.status === 'closed') {
                      displayText += '（已关闭）';
                      optionClass = 'dorm-status-closed';
                    }
                    
                    // 显示宿舍当前人数/总容量
                    if (dorm.capacity !== undefined && dorm.currentOccupancy !== undefined) {
                      displayText += ` [${dorm.currentOccupancy}/${dorm.capacity}]`;
                    }
                    
                    return (
                      <option 
                        key={dorm.id} 
                        value={dorm.id}
                        className={optionClass}
                      >
                        {displayText}
                      </option>
                    );
                  })
              ) : (
                <option value="" disabled>暂无可用宿舍</option>
              )}
            </select>
            {errors.dormitoryId && <span className="error-message">{errors.dormitoryId}</span>}
            <small style={{color: '#666', fontSize: '0.875rem', marginTop: '0.25rem', display: 'block'}}>
              提示：
              <span style={{color: '#999'}}> 蓝色=维修中 | 红色=已关闭 | 格式：楼栋-房间号 [当前人数/总容量]</span>
            </small>
          </div>
          
          <div className="form-section">
            <h3>紧急联系人信息</h3>
          <div className="form-row">
            <div className="form-group">
              <label htmlFor="emergencyContact.name">姓名</label>
              <input
                type="text"
                id="emergencyContact.name"
                name="emergencyContact.name"
                value={formData.emergencyContact?.name || ''}
                onChange={handleInputChange}
                placeholder="请输入联系人姓名"
              />
            </div>
            
            <div className="form-group">
              <label htmlFor="emergencyContact.relationship">关系</label>
              <input
                type="text"
                id="emergencyContact.relationship"
                name="emergencyContact.relationship"
                value={formData.emergencyContact?.relationship || ''}
                onChange={handleInputChange}
                placeholder="请输入与学生关系"
              />
            </div>
            
            <div className="form-group">
              <label htmlFor="emergencyContact.phone">联系电话</label>
              <input
                type="tel"
                id="emergencyContact.phone"
                name="emergencyContact.phone"
                value={formData.emergencyContact?.phone || ''}
                onChange={handleInputChange}
                placeholder="请输入联系电话"
              />
            </div>
          </div>
          </div>

          <div className="modal-footer">
            <button type="button" className="btn-cancel" onClick={handleClose}>
              取消
            </button>
            <button 
              type="submit" 
              className="btn-submit"
              disabled={isSubmitting}
            >
              {isSubmitting ? (
                <span>{isEditing ? '保存中...' : '添加中...'}</span>
              ) : (
                <span>{isEditing ? '保存修改' : '添加学生'}</span>
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default AddEditStudentModal;